#include "AdminMenu.h"
#include "ui_AdminMenu.h"
#include "PermissionBitsChoseMenu.h"


AdminMenu::AdminMenu(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::AdminMenu)
{
    ui->setupUi(this);
    AdminMenu::initMenu();
}

AdminMenu::AdminMenu(User user,QWidget* parent)
    :QMainWindow(parent),ui(new Ui::AdminMenu),m_operatorUserInfo(user)
{
    ui->setupUi(this);
    AdminMenu::initMenu();
}

AdminMenu::~AdminMenu()
{
    delete ui;
}

/*=================================<初始化界面函数>=================================*/
void AdminMenu::initMenu()
{
    ui->lb_userName->setText(m_operatorUserInfo.getName());
    ui->lb_userRole->setText(reRoleMap[m_operatorUserInfo.getRole()]);

    setWindowIcon(QIcon(":/image/CMSISIcom.svg"));

    this->setWindowTitle("管理员界面");

    ui->tbtn_userManager->setStatusTip("人员管理界面");
    ui->tbtn_log->setStatusTip("日志管理界面");
    ui->btn_exit->setStatusTip("退出系统");
    ui->lb_userName->setStatusTip(QString("当前用户的用户名：%1").arg(m_operatorUserInfo.getName()));
    ui->lb_userRole->setStatusTip(QString("当前用户的角色：%1").arg(reRoleMap[m_operatorUserInfo.getRole()]));

    QWidget* tmpNullWidget = new QWidget;
    ui->stackedWidget->addWidget(tmpNullWidget);//空权限页面，后面可以改改这里

    if(m_operatorUserInfo.getPermissionBits() & static_cast<qint64>(UPBits::USER_ADMIN_SHOW))
        ui->stackedWidget->setCurrentWidget(ui->page_userManage);
    else if(m_operatorUserInfo.getPermissionBits() & static_cast<qint64>(UPBits::USER_ADMIN_LOG))
        ui->stackedWidget->setCurrentWidget(ui->page_logManage);
    else
        ui->stackedWidget->setCurrentWidget(tmpNullWidget);


    connect(ui->btn_exit,&QPushButton::clicked,this,&AdminMenu::close);
    connect(ui->tbtn_userManager,&QToolButton::clicked,this,[&]()
            {
                if(!(m_operatorUserInfo.getPermissionBits() & static_cast<qint64>(UPBits::USER_ADMIN_SHOW)))
                {
                    QMessageBox::information(this,"权限相关提示","你没有查看用户信息的权限");
                    return;
                }
                ui->stackedWidget->setCurrentWidget(ui->page_userManage);
            });
    connect(ui->tbtn_log,&QToolButton::clicked,this,[&]()
            {
                if(!(m_operatorUserInfo.getPermissionBits() & static_cast<qint64>(UPBits::USER_ADMIN_LOG)))
                {
                    QMessageBox::information(this,"权限相关提示","你没有查看日志的权限");
                    return;
                }
                ui->stackedWidget->setCurrentWidget(ui->page_logManage);
            });

    m_DBManager = DatabaseManager::getInstance();
    try{
        m_DBManager->initDatabase();
    }catch(const std::exception& e)
    {
        QMessageBox::critical(this,"用户管理页面初始化提示",e.what());
    }

    AdminMenu::initUserManagePageMenu();
    AdminMenu::initLogManagePageMenu();
}

/*++++++++++++++<初始化用户管理界面函数>++++++++++++++*/
void AdminMenu::initUserManagePageMenu()
{
    ui->userManage_le_permissionBits->setStatusTip("权限位");
    ui->userManage_btn_add->setStatusTip("添加的用户id不可以重复");
    ui->userManage_btn_delete->setStatusTip("删除用户之前请先选择一条数据");
    ui->userManage_btn_update->setStatusTip("选中数据之后点击除了编辑框之外的内容都会退出选中状态");
    ui->userManage_btn_find->setStatusTip("按照姓名模糊查询");
    ui->userManage_le_find->setStatusTip("请输入要查找用户的姓名");
    ui->userManage_btn_refresh->setStatusTip("刷新用户数据列表");

    m_userSqlQueryModel = new QSqlQueryModel(this);
    m_userSqlQueryModel->setQuery(m_DBManager->getQueryForAll("user"));

    m_userSqlQueryModel->setHeaderData(0,Qt::Horizontal,tr("ID"));
    m_userSqlQueryModel->setHeaderData(1,Qt::Horizontal,tr("姓名"));
    m_userSqlQueryModel->setHeaderData(2,Qt::Horizontal,tr("密码"));
    m_userSqlQueryModel->setHeaderData(3,Qt::Horizontal,tr("权限位"));
    m_userSqlQueryModel->setHeaderData(4,Qt::Horizontal,tr("角色"));
    m_userSqlQueryModel->setHeaderData(5,Qt::Horizontal,tr("用户角色描述"));

    ui->userManage_tv_userInfoList->setSelectionBehavior(QAbstractItemView::SelectRows); // 单击选中整行
    ui->userManage_tv_userInfoList->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);//宽度自动伸展
    ui->userManage_tv_userInfoList->verticalHeader()->setVisible(false);//不显示行号

    ui->userManage_tv_userInfoList->setModel(m_userSqlQueryModel);

    connect(ui->userManage_tv_userInfoList,&QTableView::clicked,this,&AdminMenu::m_on_userManage_tv_userInfoList_clicked);
    connect(ui->userManage_btn_add,&QPushButton::clicked,this,&AdminMenu::m_on_userManage_btn_add_clicked);
    connect(ui->userManage_btn_delete,&QPushButton::clicked,this,&AdminMenu::m_on_userManage_btn_delete_clicked);
    connect(ui->userManage_btn_update,&QPushButton::clicked,this,&AdminMenu::m_on_userManage_btn_update_clicked);
    connect(ui->userManage_btn_find,&QPushButton::clicked,this,&AdminMenu::m_on_userManage_btn_find_clicked);
    connect(ui->userManage_btn_refresh,&QPushButton::clicked,this,[this](){m_tv_userInfoListSelectflag=false;m_userSqlQueryModel->setQuery(m_DBManager->getQueryForAll("user"));});
    connect(ui->userManage_tbtn_permissionBitsChose,&QToolButton::clicked,this,&AdminMenu::m_on_userManage_tbtn_permissionBitsChose_clicked);

    connect(ui->userManage_rbtn_roleAdmin,&QRadioButton::clicked,this,[this](){ui->userManage_le_role->setText(reRoleMap[Role::ADMIN]);});
    connect(ui->userManage_rbtn_roleUserInfo,&QRadioButton::clicked,this,[this](){ui->userManage_le_role->setText(reRoleMap[Role::USER_INFO]);});
    connect(ui->userManage_rbtn_roleUserStoreIO,&QRadioButton::clicked,this,[this](){ui->userManage_le_role->setText(reRoleMap[Role::USER_STORE_IO]);});
    connect(ui->userManage_rbtn_roleUserStoreCheck,&QRadioButton::clicked,this,[this](){ui->userManage_le_role->setText(reRoleMap[Role::USER_STORE_CHECK]);});
}

/*++++++++++++++<初始化日志管理界面函数>++++++++++++++*/
void AdminMenu::initLogManagePageMenu()
{
    ui->logManage_dte_find_operationTimeStart->setCalendarPopup(true);
    ui->logManage_dte_find_operationTimeEnd->setCalendarPopup(true);

    //筛选条件逻辑
    ui->logManage_le_find_operatorName->setEnabled(static_cast<bool>(ui->logManage_cb_operatorName->checkState()));
    connect(ui->logManage_cb_operatorName,&QCheckBox::stateChanged,this,[this](int state)
            {
                ui->logManage_le_find_operatorName->setEnabled(static_cast<bool>(state));
            });

    ui->logManage_le_find_operatorRole->setEnabled(static_cast<bool>(ui->logManage_cb_operatorRole->checkState()));
    connect(ui->logManage_cb_operatorRole,&QCheckBox::stateChanged,this,[this](int state)
            {
                ui->logManage_le_find_operatorRole->setEnabled(static_cast<bool>(state));
            });

    ui->logManage_dte_find_operationTimeStart->setEnabled(static_cast<bool>(ui->logManage_cb_operationTime->checkState()));
    connect(ui->logManage_cb_operationTime,&QCheckBox::stateChanged,this,[this](int state)
            {
                ui->logManage_dte_find_operationTimeStart->setEnabled(static_cast<bool>(state));
            });

    ui->logManage_dte_find_operationTimeEnd->setEnabled(static_cast<bool>(ui->logManage_cb_operationTime->checkState()));
    connect(ui->logManage_cb_operationTime,&QCheckBox::stateChanged,this,[this](int state)
            {
                ui->logManage_dte_find_operationTimeEnd->setEnabled(static_cast<bool>(state));
            });

    m_logSqlQueryModel = new LogEntryManagerSqlQueryModel;
    m_logSqlQueryModel->setQuery(m_DBManager->getQueryForAll("logEntry"));

    m_logSqlQueryModel->setHeaderData(0,Qt::Horizontal,tr("日志ID"));
    m_logSqlQueryModel->setHeaderData(1,Qt::Horizontal,tr("操作时间"));
    m_logSqlQueryModel->setHeaderData(2,Qt::Horizontal,tr("操作人员姓名"));
    m_logSqlQueryModel->setHeaderData(3,Qt::Horizontal,tr("操作人员角色"));
    m_logSqlQueryModel->setHeaderData(4,Qt::Horizontal,tr("操作描述"));

    ui->logManage_tv_logInfoList->setSelectionBehavior(QAbstractItemView::SelectRows); // 单击选中整行
    ui->logManage_tv_logInfoList->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);//宽度自动伸展
    ui->logManage_tv_logInfoList->verticalHeader()->setVisible(false);//不显示行号

    ui->logManage_tv_logInfoList->setModel(m_logSqlQueryModel);

    connect(ui->logManage_tv_logInfoList,&QTableView::clicked,this,&AdminMenu::m_on_logManage_tv_logInfoList_clicked);
}

/*=================================<鼠标松开事件>=================================*/
void AdminMenu::mouseReleaseEvent(QMouseEvent *event)
{
    if(event->button() == Qt::LeftButton)
    {
        m_tv_userInfoListSelectflag = false;

        ui->userManage_le_id->clear();
        ui->userManage_le_name->clear();
        ui->userManage_le_password->clear();
        ui->userManage_le_permissionBits->clear();
        ui->userManage_le_role->clear();
        ui->userManage_te_roleDescription->clear();
    }
    QWidget::mouseReleaseEvent(event);
    qDebug() << "鼠标松开事件，是否选中数据:" << m_tv_userInfoListSelectflag;
}

/*=================================<用户管理界面的按钮槽函数>=================================*/
void AdminMenu::m_on_userManage_tv_userInfoList_clicked(const QModelIndex &index)
{
    ui->userManage_le_id->setText(m_userSqlQueryModel->data(this->m_userSqlQueryModel->index(index.row(),0)).toString());
    ui->userManage_le_name->setText(m_userSqlQueryModel->data(this->m_userSqlQueryModel->index(index.row(),1)).toString());
    ui->userManage_le_password->setText(m_userSqlQueryModel->data(this->m_userSqlQueryModel->index(index.row(),2)).toString());
    ui->userManage_le_permissionBits->setText(m_userSqlQueryModel->data(this->m_userSqlQueryModel->index(index.row(),3)).toString());
    ui->userManage_le_role->setText(m_userSqlQueryModel->data(this->m_userSqlQueryModel->index(index.row(),4)).toString());
    ui->userManage_te_roleDescription->setText(m_userSqlQueryModel->data(this->m_userSqlQueryModel->index(index.row(),5)).toString());

    switch(roleMap[ui->userManage_le_role->text()])
    {
    case Role::ADMIN: ui->userManage_rbtn_roleAdmin->click();break;
    case Role::USER_INFO:ui->userManage_rbtn_roleUserInfo->click();break;
    case Role::USER_STORE_IO:ui->userManage_rbtn_roleUserStoreIO->click();break;
    case Role::USER_STORE_CHECK:ui->userManage_rbtn_roleUserStoreCheck->click();break;
    default:qDebug() << "选中数据的角色枚举数据有误";break;
    }

    m_tv_userInfoListSelectflag = true;
    m_tv_userInfoListSelectUserId = m_userSqlQueryModel->data(this->m_userSqlQueryModel->index(index.row(),0)).toInt();
    qDebug() << "点击列表，是否选中数据:" << m_tv_userInfoListSelectflag << m_tv_userInfoListSelectUserId;
}

void AdminMenu::m_on_userManage_btn_add_clicked()
{
    QString hintTitle = "添加用户提示";
    m_tv_userInfoListSelectflag=false;

    if(!(m_operatorUserInfo.getPermissionBits() & static_cast<qint64>(UPBits::USER_ADMIN_ADD)))
    {
        QMessageBox::information(this,hintTitle,"你没有添加用户信息的权限");
        return;
    }

    if(ui->userManage_le_id->text().isEmpty() || ui->userManage_le_name->text().isEmpty() || ui->userManage_le_password->text().isEmpty())
    {
        QMessageBox::information(this,hintTitle,"用户必要信息缺失(id,姓名,密码,角色类型)");
        return;
    }

    try{
        m_DBManager->userManage_insertUserInfoRecord(User(
                ui->userManage_le_name->text(),
                ui->userManage_le_password->text(),
                ui->userManage_le_permissionBits->text().toUInt(),
                roleMap[ui->userManage_le_role->text()],
                ui->userManage_te_roleDescription->toPlainText()
            ));
    }catch(const std::exception& e)
    {
        QMessageBox::information(this,"新增用户记录提示",e.what());
        return;
    }

    m_userSqlQueryModel->setQuery(m_DBManager->getQueryForAll("user"));
    QMessageBox::information(this,hintTitle,QString("添加%1用户成功").arg(ui->userManage_le_name->text()));

    try{
        m_DBManager->logManage_insertLogRecord(LogEntry(QDateTime::currentDateTime(),
                                        m_operatorUserInfo.getName(),
                                        m_operatorUserInfo.getRole(),
                                        QString("添加了一个人员信息:[add]%1").arg(ui->userManage_le_name->text())));
    }catch(const std::exception& e)
    {
        QMessageBox::critical(this,hintTitle,e.what());
    }

}

void AdminMenu::m_on_userManage_btn_delete_clicked()
{
    QString hintTitle = "删除用户提示";

    if(!(m_operatorUserInfo.getPermissionBits() & static_cast<qint64>(UPBits::USER_ADMIN_DELETE)))
    {
        QMessageBox::information(this,hintTitle,"你没有删除用户信息的权限");
        return;
    }

    if(!m_tv_userInfoListSelectflag)
    {
        QMessageBox::information(this,hintTitle,"点击删除用户按钮之前请先选择一条数据");
        return;
    }
    m_tv_userInfoListSelectflag=false;

    try{
        m_DBManager->userManage_deleteUserInfoRecord(m_tv_userInfoListSelectUserId);
    }catch(const std::exception& e)
    {
        QMessageBox::critical(this,"删除指定用户记录提示",e.what());
        return;
    }

    m_userSqlQueryModel->setQuery(m_DBManager->getQueryForAll("user"));
    QMessageBox::information(this,hintTitle,"删除" + ui->userManage_le_name->text() +"成功");
    try{
        m_DBManager->logManage_insertLogRecord(LogEntry(QDateTime::currentDateTime(),
                                        m_operatorUserInfo.getName(),
                                        m_operatorUserInfo.getRole(),
                                        QString("删除了一个人员信息:[delete]%1").arg(ui->userManage_le_name->text())));
    }catch(const std::exception& e)
    {
        QMessageBox::critical(this,hintTitle,e.what());
        return;
    }
}

void AdminMenu::m_on_userManage_btn_update_clicked()
{
    QString hintTitle = "修改用户提示";

    if(!(m_operatorUserInfo.getPermissionBits() & static_cast<qint64>(UPBits::USER_ADMIN_MODIFY)))
    {
        QMessageBox::information(this,hintTitle,"你没有修改用户信息的权限");
        return;
    }

    if(!m_tv_userInfoListSelectflag)
    {
        QMessageBox::information(this,hintTitle,"点击修改用户按钮之前请先选择一条数据");
        return;
    }
    m_tv_userInfoListSelectflag=false;

    if(ui->userManage_le_id->text().isEmpty() || ui->userManage_le_name->text().isEmpty() || ui->userManage_le_password->text().isEmpty())
    {
        QMessageBox::information(this,hintTitle,"修改用户必要信息缺失(id,姓名,密码,角色类型)");
        return;
    }

    try{
        m_DBManager->userManage_updateUserInfoRecord(User(ui->userManage_le_name->text(),
                                                          ui->userManage_le_password->text(),
                                                          ui->userManage_le_permissionBits->text().toUInt(),
                                                          roleMap[ui->userManage_le_role->text()],
                                                          ui->userManage_te_roleDescription->toPlainText()),
                                                     m_tv_userInfoListSelectUserId);
    }catch(const std::exception& e)
    {
        QMessageBox::critical(this,hintTitle,e.what());
        return;
    }

    m_userSqlQueryModel->setQuery(m_DBManager->getQueryForAll("user"));
    QMessageBox::information(this,hintTitle,QString("修改%1用户成功").arg(ui->userManage_le_name->text()));

    try{
        m_DBManager->logManage_insertLogRecord(LogEntry(QDateTime::currentDateTime(),
                                        m_operatorUserInfo.getName(),
                                        m_operatorUserInfo.getRole(),
                                        QString("修改了一个人员信息:[update]%1").arg(ui->userManage_le_name->text())));
    }catch(const std::exception& e)
    {
        QMessageBox::critical(this,hintTitle,e.what());
        return;
    }
}

void AdminMenu::m_on_userManage_btn_find_clicked()
{
    QString hintTitle = "查询用户提示";

    if(!(m_operatorUserInfo.getPermissionBits() & static_cast<qint64>(UPBits::USER_ADMIN_FIND)))
    {
        QMessageBox::information(this,hintTitle,"你没有查找用户信息的权限");
        return;
    }

    if(ui->userManage_le_find->text().isEmpty())
    {
        QMessageBox::information(this,hintTitle,"请输入要查询用户的姓名，支持模糊查询");
    }

    try{
        m_userSqlQueryModel->setQuery(m_DBManager->userManage_findUserInfoRecord(ui->userManage_le_find->text()));
    }catch(const std::exception& e)
    {
        QMessageBox::critical(this,hintTitle,e.what());
    }

    try{
        m_DBManager->logManage_insertLogRecord(LogEntry(QDateTime::currentDateTime(),
                                        m_operatorUserInfo.getName(),
                                        m_operatorUserInfo.getRole(),
                                        QString("查询了人员信息:[find]%1").arg(ui->userManage_le_find->text())));
    }catch(const std::exception& e)
    {
        QMessageBox::critical(this,hintTitle,e.what());
        return;
    }
}

void AdminMenu::m_on_userManage_tbtn_permissionBitsChose_clicked()
{
    PB_t tmpPB = ui->userManage_le_permissionBits->text().toUInt();
    PermissionBitsChoseMenu* tmpPermissionBitsChoseMenu = new PermissionBitsChoseMenu(roleMap[ui->userManage_le_role->text()],tmpPB,this);
    tmpPermissionBitsChoseMenu->setAttribute(Qt::WA_DeleteOnClose);//关闭自动线销毁
    connect(tmpPermissionBitsChoseMenu,&PermissionBitsChoseMenu::dataConfirmed,this,[=](PB_t pb)mutable
            {
                ui->userManage_le_permissionBits->setText(QString("%1").arg(pb));
            });
    tmpPermissionBitsChoseMenu->exec();
}

/*=================================<日志管理界面的按钮槽函数>=================================*/
void AdminMenu::m_on_logManage_tv_logInfoList_clicked(const QModelIndex &index)
{
    ui->logManage_le_logId->setText(m_logSqlQueryModel->data(this->m_logSqlQueryModel->index(index.row(),0)).toString());
    ui->logManage_le_operationTIme->setText(m_logSqlQueryModel->data(this->m_logSqlQueryModel->index(index.row(),1)).toString());
    ui->logManage_le_operatorName->setText(m_logSqlQueryModel->data(this->m_logSqlQueryModel->index(index.row(),2)).toString());
    ui->logManage_le_operatorRole->setText(m_logSqlQueryModel->data(this->m_logSqlQueryModel->index(index.row(),3)).toString());
    ui->logManage_te_operationDescribe->setText(m_logSqlQueryModel->data(this->m_logSqlQueryModel->index(index.row(),4)).toString());

}

/*=================================<自定义QSqlQueryModel>=================================*/
//自定义QSqlQueryModel，为了将字段中的毫秒时间戳转换成yyyy-MM-dd HH:mm:ss.zzz直接显示
LogEntryManagerSqlQueryModel::LogEntryManagerSqlQueryModel(QObject *parent): QSqlQueryModel(parent)
{

}

QVariant LogEntryManagerSqlQueryModel::data(const QModelIndex &index, int role) const
{
    if(role == Qt::DisplayRole)
    {
        int column = index.column();
        if(column == 1)//日期（毫秒时间戳）
        {
            return QDateTime::fromMSecsSinceEpoch(
                       QSqlQueryModel::data(index,role).toLongLong())
                .toString("yyyy-MM-dd HH:mm:ss.zzz");
        }
        if(column == 3)//用户角色
        {
            return reRoleMap[static_cast<Role>(QSqlQueryModel::data(index,role).toInt())];
        }
        return QSqlQueryModel::data(index,role);
    }
    return QSqlQueryModel::data(index, role);
}
